package com.yueyin;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.yueyin.databinding.ActivityMainBinding;
import com.yueyin.databinding.FragmentCatalogBinding;
import com.yueyin.databinding.FragmentMainBinding;
import com.yueyin.ui.main.Data;
import com.yueyin.ui.main.MusicList;
import com.yueyin.ui.main.MusicScan;
import com.yueyin.ui.main.MyAdapter;
import com.yueyin.ui.main.MyBroadcastReceiver;
import com.yueyin.ui.main.PlayLogic;
import com.yueyin.ui.main.SQLiteHelper;
import com.yueyin.ui.main.TouchEvent;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {

    SectionsPagerAdapter mSectionsPagerAdapter;

    PlayLogic playLogic = null;
    FragmentCatalog fragmentCatalog;

    List<Fragment> fragmentList = new ArrayList<>();
    MyBroadcastReceiver mbr = null;
    boolean isRegistered = false;//判断是否注册广播，用于关闭广播
    ActivityMainBinding binding;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        //binding = ActivityMainBinding.inflate(getLayoutInflater());

        playLogic = new PlayLogic(getApplicationContext());

        fragmentCatalog = new FragmentCatalog(getApplicationContext(), playLogic);

        FragmentMain fragmentMain = new FragmentMain(getApplicationContext(), playLogic);

        playLogic.setFragmentMain(fragmentMain);
        playLogic.setFragmentCatalog(fragmentCatalog);

        fragmentList.add(fragmentCatalog);
        fragmentList.add(fragmentMain);

        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), 0, fragmentList);
        ViewPager mViewPager = findViewById(R.id.pager);
        //ViewPager mViewPager = binding.getRoot();
        mViewPager.setAdapter(mSectionsPagerAdapter);

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.intent.action.HEADSET_PLUG");
        mbr = new MyBroadcastReceiver();
        registerReceiver(mbr, intentFilter);
        isRegistered = true;

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    /**
     * 返回键后台运行
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            moveTaskToBack(false);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 菜单键
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.exit) {
            finish();
            playLogic.getMedia().release();
            if (isRegistered) {
                unregisterReceiver(mbr);
            }
            System.exit(0);
            return true;
        } else if (id == R.id.scan) {
            finish();
            Intent intent = new Intent(this, MusicScan.class);
            startActivity(intent);
            return true;
        } else if (id == R.id.clearRecord) {
            fragmentCatalog.binding.LVMusicList.setAdapter(null);
            new SQLiteHelper(getApplicationContext()).clearTable();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * fragment页面
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        List<Fragment> list;

        public SectionsPagerAdapter(FragmentManager fm, int behavior, List<Fragment> fragmentList) {
            super(fm, behavior);
            list = fragmentList;
        }

        @NonNull
        @Override
        public Fragment getItem(int position) {
            return fragmentList.get(position);
        }

        @Override
        public int getCount() {
            return 2;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            Locale locale = Locale.getDefault();
            switch (position) {
                case 0:
                    return getString(R.string.fragment_catalog).toUpperCase(locale);
                case 1:
                    return getString(R.string.fragment_main).toUpperCase(locale);
            }
            return null;
        }
    }

    /**
     * 目录页
     */
    public static class FragmentCatalog extends Fragment {

        FragmentCatalogBinding binding;

        public List<Data> dataList;

        public Context context;
        PlayLogic playLogic;

        public FragmentCatalog(Context context, PlayLogic playLogic) {
            this.context = context;
            this.playLogic = playLogic;
        }

        @Override
        public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            binding = FragmentCatalogBinding.inflate(inflater, container, false);

            //binding.getRoot().setBackgroundResource(R.mipmap.bg);

            // 音乐列表
            dataList = new MusicList(getActivity()).showMusicList();

            playLogic.setTotalMusicNum(dataList.size());

            int index = 1;

            for (Data data : dataList) {
                data.setIndex(index);
                index++;
            }

            MyAdapter adapter = new MyAdapter(getActivity(), dataList, binding);
            binding.LVMusicList.setAdapter(adapter);

            // 添加列表点击事件
            binding.LVMusicList.setOnItemClickListener(new TouchEvent.OnListItemClick(playLogic));

            return binding.getRoot();
        }
    }

    /**
     * 主页面
     */
    public static class FragmentMain extends Fragment {

        public FragmentMainBinding binding;
        PlayLogic playLogic;
        public Context context;

        public FragmentMain(Context context, PlayLogic playLogic) {
            this.context = context;
            this.playLogic = playLogic;
        }

        @Override
        public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

            binding = FragmentMainBinding.inflate(inflater, container, false);

            binding.ivPlayModel.setOnClickListener(new TouchEvent.OnPlayModelClick(playLogic));
            binding.ivPlayPause.setOnClickListener(new TouchEvent.OnPlayPauseClick(playLogic));
            binding.ivLast.setOnClickListener(new TouchEvent.OnLastClick(playLogic));
            binding.ivNext.setOnClickListener(new TouchEvent.OnNextClick(playLogic));
            binding.ivList.setOnClickListener(new TouchEvent.OnMenuClick(playLogic));
            binding.SK.setOnSeekBarChangeListener(new TouchEvent.OnSKChanged(playLogic, binding.SK));

            return binding.getRoot();
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mbr != null) {
            unregisterReceiver(mbr);
        }
    }
}
